package com.smartwebx.ha.biz.assign.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.smartwebx.ha.biz.assign.HaRoleManager;
import com.smartwebx.ha.dal.assign.bean.HaRole;
import com.smartwebx.ha.dal.assign.bean.HaRoleExample;
import com.smartwebx.ha.dal.assign.bean.HaUserExample;
import com.smartwebx.ha.dal.assign.dao.HaRoleMapper;
import com.smartwebx.ha.dal.assign.dao.HaUserMapper;
import com.smartwebx.ha.dal.util.CommonsUtil;
import com.smartwebx.ha.dal.util.MyFunctions;

@Service
public class HaRoleManagerImpl implements HaRoleManager {

	@Autowired
	private HaRoleMapper haRoleDao;
	@Autowired
	private HaUserMapper haUserDao;

	@Override
	public List<HaRole> findAll() {
		HaRoleExample haRoleExample = new HaRoleExample();
		haRoleExample.setOrderByClause("id desc");
		List<HaRole> allRoles = haRoleDao.selectByExample(haRoleExample);
		return allRoles;
	}

	@Override
	public HaRole findOne(int roleId) {
		return haRoleDao.selectByPrimaryKey(roleId);
	}

	@Override
	public boolean delRole(String roleIds) {
		HaRoleExample roleExample = new HaRoleExample();
		HaUserExample userExample = new HaUserExample();
		Iterable<String> ids = Splitter.on(",").trimResults().split(roleIds);
		List<Integer> roleIdList = FluentIterable.from(ids)
				.transform(MyFunctions.parseNumberFunctionFor(Integer.class))
				.toList();
		boolean state = false;

		if (roleIdList.isEmpty()) {
			state = true;
		} else {
			roleExample.createCriteria().andIdIn(roleIdList);
			userExample.createCriteria().andRoleIdIn(roleIdList);

			int state1 = haRoleDao.deleteByExample(roleExample);
			int state2 = haUserDao.deleteByExample(userExample);

			if (state1 >= 1 && state2 >= 1) {
				state = true;
			}
		}
		return state;
	}

	@Override
	public boolean addRole(HaRole role) {
		int state = haRoleDao.insert(role);
		return CommonsUtil.checkedTrueOrFalse(state);
	}

	@Override
	public boolean updateRole(HaRole role) {
		int state = haRoleDao.updateByPrimaryKeySelective(role);
		return CommonsUtil.checkedTrueOrFalse(state);
	}

}
